/**
 * Copyright (C) 2017 - 2020 https://github.com/joewee
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.workflow.price;

import com.bifrost.constant.ShipmentMode;
import com.bifrost.constant.ShippingType;
import com.bifrost.entity.CountryArea;
import com.bifrost.entity.MerchantStore;
import com.bifrost.entity.Order;
import com.bifrost.exception.PricingException;
import com.bifrost.repository.MerchantShipmentRegionRepository;
import com.bifrost.repository.MerchantShipmentRepository;
import com.bifrost.repository.ProductSkuRepository;
import com.bifrost.service.ShippingService;
import com.bifrost.workflow.BaseActivity;
import com.bifrost.workflow.ProcessContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * <p>
 * 店铺模式： 即整个店铺采用统一的运费标准，可设置收取固定费用，例如收取固定运费10元；或者满额包邮。
 * </p>
 * <p>单品运费模式： 为店铺内的每个商品设置自己独有的运费收取方式，每个商品的运费独立计算（一个订单下属于统一单品运费模板的商品，一起计算），
 * 当一个订单的商品属于多个单品运费时，可以选择按叠加/取最大值的方式计算订单最终的运费值
 * </p>
 * <p>
 * 混合模式:店铺运费模板与单品运费模板同时生效，店铺运费优先判断当订单金额满足运费上设置的免邮金额，按照店铺运费模式计算，不满足时，按照单品运费计算
 * 如果单品运费模版上设置了单品运费优先店铺运费，单品运费模版绑定的商品的运费单独计算，即使订单金额满足店铺免邮，也会按照单品运费模版计算运费
 * </p>
 *
 * @author joewee
 * @version 1.0.0
 * @Date 2017/11/14 13:53
 */
@Component("shippingActivity")
public class ShippingActivity extends BaseActivity<ProcessContext<Order>> {
    public static final int ORDER = 3000;
    private static final Logger LOGGER = LoggerFactory.getLogger(ShippingActivity.class);
    @Autowired
    MerchantShipmentRepository merchantShipmentRepository;
    @Autowired
    MerchantShipmentRegionRepository merchantShipmentRegionRepository;
    @Autowired
    ProductSkuRepository productSkuRepository;
    @Autowired
    ShippingService shippingService;

    public ShippingActivity() {
        setOrder(ORDER);
    }

    @Override
    public ProcessContext<Order> execute(ProcessContext<Order> context) throws Exception {
        Order order = context.getSeedData();
        if (ShippingType.SELF_DELIVERY.equalsIgnoreCase(order.getShippingType())) {
            context.getSeedData().setTotalShippingFee(BigDecimal.ZERO);
        }else if(ShippingType.DELIVERY.equalsIgnoreCase(order.getShippingType())||ShippingType.BOTH.equalsIgnoreCase(order.getShippingType())) {
            MerchantStore store = order.getMerchantStore();
            if (store == null) {
                throw new PricingException("订单所属店铺为空");
            }
            CountryArea deliveryDistrict = order.getDeliveryDistrict();
            //未设置收货地址-首次确认订单
            if (deliveryDistrict == null) {
                order.setTotalShippingFee(BigDecimal.ZERO);
                return context;
            }
            //店铺模式
            if (ShipmentMode.STORE.equalsIgnoreCase(store.getShipmentMode())) {
                order.setTotalShippingFee(shippingService.shippingPricingByStoreTemplate(store, order));
            }//单品运费模板
            else if (ShipmentMode.SKU.equalsIgnoreCase(store.getShipmentMode())) {
                order.setTotalShippingFee(shippingService.shippingPricingBySkuTemplate(order, deliveryDistrict));
            } else if (ShipmentMode.MIXED.equalsIgnoreCase(store.getShipmentMode())) {
                order.setTotalShippingFee(shippingService.shippingPricingByMixedTemplate(order, deliveryDistrict));
            } else {
                LOGGER.warn(String.format("店铺：%d-%s未设置运费模式", store.getMerchantId(), store.getStoreName()));
                order.setTotalShippingFee(BigDecimal.ZERO);
            }

        }else {
            throw new PricingException("不支持的配送类型");
        }
        return context;
    }
}
